from fastapi import FastAPI
from afast_core.core_plugins.pluginbase import IBasePlugin as BasePlugin
from pydantic import BaseSettings as Settings
from afast_core.core_db.peewee_postgresql import PeeweeSyncPooledPostgresqlClient


class PeeweePluginClient(PeeweeSyncPooledPostgresqlClient, BasePlugin):
    '''
    使用示例：
    PeeweePluginClient(core_app=core_app, configs=ASyncAioRedisPluginClient.RedisSettings(
        #   redis://[[username]:[password]]@localhost:6379/0
        #   rediss://[[username]:[password]]@localhost:6379/0
        #   unix://[[username]:[password]]@/path/to/socket.sock?databases=0
        from_url= "redis://127.0.0.1:6379/0"
    ))
    '''

    # 设置插件默认的参数信息
    name = 'PeeweePluginClient'

    class PeeweeSettings(Settings):
        db_name: str
        db_user: str
        db_pass: str
        db_host: str = '127.0.0.1'
        db_port: int = 5432
        max_connections: int = 60
        stale_timeout: int = 300
        timeout: int = 20

    def setup(self, app: FastAPI, name: str = None, *args, **kwargs):
        """插件初始化"""
        self.app = app
        self._sync_peewee = None

        @app.on_event("startup")
        async def startup_event():
            self._peewee_database = await self.init_sync_pooled_postgresql(pgconf_setting=self.settings)
            app.sync_peewee = self._sync_peewee
            
        @app.on_event("shutdown")
        async def shutdown_event():
            pass
